package com.bree.erp.data.xls.imp.sheet;

import javax.persistence.EntityManager;

import com.bree.erp.data.xls.imp.AbstractSheet;
import com.bree.erp.entity.GroupType;
import com.bree.erp.entity.User;
import com.bree.erp.service.GroupService;
import com.bree.erp.service.UserService;
import com.bree.erp.service.stateless.GroupServiceBean;
import com.bree.erp.service.stateless.UserServiceBean;

import jxl.Sheet;

public class UserSheet extends AbstractSheet {

	public UserSheet(Sheet sheet) {
		super(sheet);
	}

	@Override
	public void importSheet(EntityManager em) {
		
		Sheet sheet = this.getSheet();

		UserService userService = new UserServiceBean(em);
		GroupService groupService = new GroupServiceBean(em);

		for (int row = 1; row < sheet.getRows(); row++) {
			
			em.getTransaction().begin();

			String firstName = sheet.getCell(0, row).getContents().trim();
			String lastName = sheet.getCell(1, row).getContents().trim();
			String email = sheet.getCell(2, row).getContents().trim();
			String password = sheet.getCell(3, row).getContents().trim();

			User user = userService
					.create(email, password, firstName, lastName);
			
			em.getTransaction().commit();
			

			em.getTransaction().begin();

			for (int col = 4; col < sheet.getColumns(); col++) {
				String groupName = sheet.getCell(col, row).getContents().trim();

				if (groupName.length() > 0) {
					groupService.create(user, GroupType.valueOf(groupName));
				}
			}
			

			em.getTransaction().commit();
			

		}

	}

}
